
Berta.EditorManager.addPlugin('RTE', new Class(function() {

	return {
		extend: Berta.Editor,
		pluginName: 'RTE',
		
		// defaults for this particular plugin
		defaults: {			
			pluginOptions: { 
				tinymce: {
					// Location of TinyMCE script
					script_url : '/lib/tiny_mce/tiny_mce.js',
					content_css : '/css/rte_content.css',
					editor_css : '/css/rte_ui.css',
		
					theme : "advanced",
					plugins: "save,paste",
	
					width : "600px", height : "300px",
					
					//save,|,
					theme_advanced_buttons1 : "pasteword,|,undo,redo,|,bold,italic,removeformat,cleanup,styleprops,|,bullist,numlist,outdent,indent,|,hr,link,unlink,|,code",
					theme_advanced_buttons2 : "",
					theme_advanced_buttons3 : "",
					theme_advanced_path : false,
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "",
					theme_advanced_resizing : true,
	
					save_enablewhendirty : false,
					save_onsavecallback: null, // set in validate()
	
					
					valid_elements : "iframe[*],object[*],embed[*],param[*],form[*],input[*],textarea[*],select[*]," + 
									 "p[class],b[class],i[class],span[class],strong[class],em[class],a[href|target|class|style|title],br[*],u[class]," + 
									 "ul,li,ol,img[*],hr[class]",
					custom_elements : '',
					extended_valid_elements : '',
					convert_urls: false,
					relative_urls: false,
	
					media_use_script: false
				}
			}
		},
		
		constructor: function(options) {
			//$.log('construct RTE editor');
			
			// call the parent with pluginName=null
			// Editor defaults get extended by this.defaults and then extended by options
			Berta.Editor.call(this, options);
			
			this.originalValue = this.element.html();
			this.value = this.originalValue;
		},
		
		//   .______    __    __  .______    __       __    ______    ////////////////////////////////////////////////////////////
		//   |   _  \  |  |  |  | |   _  \  |  |     |  |  /      |   ////////////////////////////////////////////////////////////
		//   |  |_)  | |  |  |  | |  |_)  | |  |     |  | |  ,----'   ////////////////////////////////////////////////////////////
		//   |   ___/  |  |  |  | |   _  <  |  |     |  | |  |        ////////////////////////////////////////////////////////////
		//   |  |      |  `--'  | |  |_)  | |  `----.|  | |  `----.   ////////////////////////////////////////////////////////////
		//   | _|       \______/  |______/  |_______||__|  \______|   ////////////////////////////////////////////////////////////
		
		on: /* API */ function() {
			this.element.addClass('x-editable-on');
			this.element.bind('click' + this.namespace(), this._(onElementClick));
			this.appendPlaceholderIfEmpty();
			Berta.Editor.prototype.on.call(this);
		},
		
		off: /* API */ function() {
			if(this.hasFlag(Berta.Editor.flags.EDITING)) {
				this.cancel();
			}
			this.element.removeClass('x-editable-on');
			this.element.unbind('click' + this.namespace());
			this.removePlaceholder();
			Berta.Editor.prototype.off.call(this);
		},
		
		edit: /* API */ function() {
			if(this.hasFlag(Berta.Editor.flags.ON) && !this.hasFlag(Berta.Editor.flags.EDITING)) {
				Berta.Editor.prototype.startEditing.call(this);
				this._(startEditing)();
				Berta.Editor.prototype.setPanelContext.call(this);
			}
		},
		save: /* API */ function() {
			if(this.hasFlag(Berta.Editor.flags.EDITING)) {
				this.value = this.getValue();
				if(this.value != this.originalValue) this.fireChange();
				
				this._(stopEditing)();
				Berta.Editor.prototype.stopEditing.call(this);
				Berta.Editor.prototype.save.call(this, this._(onSaveComplete));
			}
		},
		cancel: /* API */ function() {
			Berta.Editor.prototype.hidePanelContext.call(this);
			if(this.hasFlag(Berta.Editor.flags.EDITING)) {
				this._(stopEditing)();
			} else if(this.hasFlag(Berta.Editor.flags.SAVING)) {
				this.saveStop();
			} else {
				this.element.html(this.originalValue);
			}
			this.value = this.originalValue;
			this.fireRevert();
			this.cleanup();
		},

		
		cleanup: function() {
			if (this.replacementElement) {
				this.element.removeClass('x-hidden')
							.data(Berta.Editor.DATA_REPLACEMENT, null);
				this.replacementElement.empty().remove();
				this.replacementElement = null;
			}
			
			if(this.hasFlag(Berta.Editor.flags.DESTROYING)) {
				this.off();
			} else {
				this.appendPlaceholderIfEmpty();
			}
		},
		
		
		
		validate: /* override */ function() {
			var that = this;
			this.options.pluginOptions.tinymce.save_onsavecallback = function() {
				that.save();
			};
			
			Berta.Editor.prototype.validate.call(this);
		},
		
		getValue: function() {
			var v;
			if (this.hasFlag(Berta.Editor.flags.EDITING)) {
				v = this.replacementElement.html();
			} else {
				v = this.value;
			}
			
			return v;
		}
	};
	
	
	
	
	//   .______   .______     __  ____    ____  ___   .___________. _______    //////////////////////////////////////////////////
	//   |   _  \  |   _  \   |  | \   \  /   / /   \  |           ||   ____|   //////////////////////////////////////////////////
	//   |  |_)  | |  |_)  |  |  |  \   \/   / /  ^  \ `---|  |----`|  |__      //////////////////////////////////////////////////
	//   |   ___/  |      /   |  |   \      / /  /_\  \    |  |     |   __|     //////////////////////////////////////////////////
	//   |  |      |  |\  \--.|  |    \    / /  _____  \   |  |     |  |____    //////////////////////////////////////////////////
	//   | _|      | _| `.___||__|     \__/ /__/     \__\  |__|     |_______|   //////////////////////////////////////////////////
		
	function onElementClick() {
		this.edit();
	}

	function startEditing() {
		
		this.removePlaceholder();
		
		// create replcementElement and add to DOM
		if(!this.replacementElement) {
			this.replacementElement = $('<div>').uniqid().html(this.element.html());
			this.element.removeClass('x-editable x-editable-on')
			this.replacementElement.css(this.element.css())
								   .css({ height: 'auto' })
			this.element.addClass('x-editable x-editable-on')
		}
		this.element.addClass('x-hidden')
					.data(Berta.Editor.DATA_REPLACEMENT, this.replacementElement.attr('id'))
					.after(this.replacementElement);
		
		// make replacementElement editable
		this.replacementElement.addClass('x-editing')
							   .tinymce(this.options.pluginOptions.tinymce);

		
		// init the mechanism to know when the editing has finished
		// set it after a timeout to avoid catching the initial click event
		setTimeout(this._(addFinishTrigger), 1);
	}
	function stopEditing() {
		this._(removeFinishTrigger)();
		this._(disableEditingOptions)(this.replacementElement);
		this.replacementElement.removeClass('x-editing');
		this.replacementElement.tinymce().remove();
	}
	
	
	
	function onSaveComplete(response) {
		if (response.error) {
			this.askIfCancelOnSaveErorr(response.errorMessage, this._(this.cancel), this._(this.edit));
		} else {
			this.value = response.json.values[this.options.variable];
			this.element.html(this.value);
			Berta.Editor.prototype.hidePanelContext.call(this);
			this.fireSave();
			
			// update original value after calling the callback, so the callback can distinguish between the two
			this.originalValue = this.value;
			
			this.cleanup();
		}
	}
	
	
	
	function addFinishTrigger() {
		// adds click event to the body that checks if the user has clicked outside the replacementElement
		this._onBodyClick = this._(onBodyClick);
		$(document.body)[0].addEventListener('click', this._onBodyClick, true); // add to capturing phase
		//$(document.body).bind('click' + this.namespace(), this._(onBodyClick));
	}
	function removeFinishTrigger() {
		// adds click event to the body that checks if the user has clicked outside the replacementElement
		$(document.body)[0].removeEventListener('click', this._onBodyClick, true);
		this._onBodyClick = null;
		//$(document.body).unbind('click' + this.namespace());
	}
	function onBodyClick(event) {
		// captures the click.Berta.Editor.RTE event and checks if the click has happened
		// outside the replacementElement. if yes, then stopEditing()
		var trg = $(event.target);
		var editorId = this.replacementElement.attr('id');
		//console.debug(self, trg, self.element, self.options.context);

		if(this.options.context != 'panel' && trg.xInPanelOrPopups()) {
			return true;


		} else if(trg.parents('#' + editorId + ',#' + editorId + '_parent').size() == 0) {
			event.stopPropagation();
			event.preventDefault();

			this.save();
			return false;
		}
	}
	
	
	// EFFECTUATING OPTIONS ...
	
	function enableEditingOptions($el) {
		// add events in namespace <namespace>.options
	};
	function disableEditingOptions($el) {
		// remove all listeners attached by startEditingOptions
		$el.unbind(this.namespace() + '.options');
	};

	
	
}()));



